package com.springboot.show_web.controller;

import com.springboot.show_web.dao.DepartmentDao;
import com.springboot.show_web.dao.EmployeeDao;
import com.springboot.show_web.entities.Department;
import com.springboot.show_web.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * Created by yaosheng on 2019/11/8.
 */
public class EmployeeController {

    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    DepartmentDao departmentDao;

    //查询员工列表所有员工，返回列表页面
    @GetMapping("/emps")
    public String list(Model model) {
        Collection<Employee> employees = employeeDao.getAll ();
        //放在请求域中
        model.addAttribute ("emps", employees);
        //Thymeleaf默认会拼串
        //classpath:/templates/xxxx.html
        return "emp/list";
    }

    //来到员工添加页面
    @GetMapping("/emp")
    public String toAddPage(Model model) {
        //来到添加页面，在页面显示
        Collection<Department> departments = departmentDao.getDepartments ();
        model.addAttribute ("depts", departments);
        return "emp/add";
    }

    //员工添加
    //SpringMVC自动将请求参数和入参对象的属性进行一一绑定，要求请求参数的名字和JavaBean入参的对象里面的属性是一致的
    @PostMapping("/emp")
    public String addEmp(Employee employee) {
        //来到员工列表页面
        System.out.println ("保存员工信息：" + employee);
        //保存员工
        //employee.save(employee);
        //redirect:表示重定向到一个地址
        //forward:表示转发到一个地址
        return "redirect:/emps";
    }

    //来到修改页面，查出当前员工，在页面回显
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id, Model model) {
        Employee employee = employeeDao.getEmpById (id);
        model.addAttribute ("emp", employee);
        //回到修改页面
        return "emp/add";
    }

    //员工修改,修改提交员工id
    @PutMapping("/emp")
    public String updateEmployee(Employee employee) {
        System.out.println ("修改的员工数据：" + employee);
        employeeDao.save (employee);
        return "redirect:/emps";
    }

    //员工删除
    @DeleteMapping("/emp/{id}")
    public String deleteEmployee(@PathVariable("id") Integer id) {
        employeeDao.deleteEmpById (id);
        return "redirect:/emps";
    }
}